package com.qhong.test.thread;

import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * Created by qhong on 2018/9/13 13:30
 **/
@Slf4j
public class test {

	@Test
	public void testFixedThreadPool() {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 10; i++) {
			final int index = i;
			fixedThreadPool.execute(() -> {
				try {
					log.info("newFixedThreadPool,index:{}", index);
				} catch (Exception e) {
					log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
				}
			});
		}
		fixedThreadPool.shutdown();
		while(true){
			if(fixedThreadPool.isTerminated()){
				log.info("endd");
				break;
			}
		}
		log.info("end");
	}

    @Test
	public void testCallable() {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
		List<Future<String>> resultList = Lists.newArrayList();
		for (int i = 0; i < 10; i++) {
			final int index = i;
			Future<String> future = fixedThreadPool.submit(() -> {
				try {
					Thread.sleep(2000);
					log.info("newFixedThreadPool,index:{}", index);
				} catch (Exception e) {
					log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
				}
				return "success";
			});
			resultList.add(future);
		}
		resultList.forEach(x -> {
			try {
				log.info("result:{}", x.get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				fixedThreadPool.shutdownNow();
				e.printStackTrace();
				return;
			}
		});
		log.info("end");
	}
}
